var req;

function Ajax() {
    var ajax;

    if (window.ActiveXObject) {
        try {
            ajax = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                ajax = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                ajax = false;
            }
        }
    } else if (window.XMLHttpRequest) {
        ajax = new XMLHttpRequest;
    } else {
        ajax = false;
    }

    return ajax;
}



function ValidaUsuario(link, loginn, senhaa) {
       
        req = new Ajax();
       
        link += loginn + "&senha=" + senhaa;
        req.open("GET", link, true);
        textcomp = document.getElementById("contact");
        req.onreadystatechange = Callbackalert;
        req.send(null);
    }

function Callbackalert() {
    if (req === null)
        return;
    if (req.readyState === 4 && req.status === 200) {
            textcomp.innerHTML = (req.responseText);
            //req = null;
        }
}






   
//####################################################################//
//Outras Funçoes
//####################################################################//
function CampoVazio(Campo){
	if (Campo.value == "") {
		alert("Campo vazio!");
		Campo.focus();
		return false;
	}
	else
		return true;
}

function Consistir(Campo,Vazio){
	if (Campo.value == Vazio) {
		alert("Campo obrigatrio. Favor preencha!");
		Campo.focus();
		return false;
	}
	else
		return true;
}


function ConverteMaiuscula(Campo) {
	Campo.value = Campo.value.toUpperCase();
}

function autoTab(input, e)  { 
  var ind = 0;
  var isNN = (navigator.appName.indexOf("Netscape")!=-1);
  var keyCode = (isNN) ? e.which : e.keyCode; 
  var nKeyCode = e.keyCode; 
  if(keyCode == 13){ 
    if (!isNN) {window.event.keyCode = 0;} // evitar o beep
    ind = getIndex(input);
    if (input.form[ind].type == 'textarea') {
      return;
    }
    ind++;
    input.form[ind].focus(); 
    if (input.form[ind].type == 'text') {
      input.form[ind].select(); 
    }
  } 

  function getIndex(input) { 
    var index = -1, i = 0, found = false; 
    while (i < input.form.length && index == -1) 
      if (input.form[i] == input) {
        index = i;
       	if (i < (input.form.length -1)) {
      	  if (input.form[i+1].type == 'hidden') {
	    index++; 
	  }
	  if (input.form[i+1].type == 'button' && input.form[i+1].id == 'tabstopfalse') {
	    index++; 
	  }
	}
      }
      else 
	i++; 
    return index; 
  }
} 

function editMask(objForm, strField, sMask, evtKeyPress) {
  var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla, nTeclaDel;

  if(navigator.appName == "Netscape") { // Netscape
    nTecla = evtKeyPress.which;
    nTeclaDel = evtKeyPress.keyCode;
  }
  else {//if(document.layers) { // Internet Explorer
    nTecla = evtKeyPress.keyCode; 
  }

  if (nTecla == 13) return true;
  if (nTecla == 8) return true;
  if (nTeclaDel == 46) return true;
  
  sValue = objForm[strField].value;
  
  if (sValue.length == sMask.length) {return;}

  // Limpa todos os caracteres de formata? que
  // j?stiverem no campo.
  sValue = sValue.toString().replace( "-", "" );
  sValue = sValue.toString().replace( "-", "" );
  sValue = sValue.toString().replace( ".", "" );
  sValue = sValue.toString().replace( ".", "" );
  sValue = sValue.toString().replace( "/", "" );
  sValue = sValue.toString().replace( "/", "" );
  sValue = sValue.toString().replace( "(", "" );
  sValue = sValue.toString().replace( "(", "" );
  sValue = sValue.toString().replace( ")", "" );
  sValue = sValue.toString().replace( ")", "" );
  sValue = sValue.toString().replace( " ", "" );
  sValue = sValue.toString().replace( " ", "" );
  sValue = sValue.toString().replace( ":", "" );
  sValue = sValue.toString().replace( ":", "" );
  fldLen = sValue.length;
  mskLen = sMask.length;

  i = 0;
  nCount = 0;
  sCod = "";
  mskLen = fldLen;

  // Incluindo os caracteres da m?ara no valor digitado
  while (i <= mskLen) {
    bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/") || (sMask.charAt(i) == ":"))
    bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))
 
    if (bolMask) {
      sCod += sMask.charAt(i);
      mskLen++;
    }
    else {
      sCod += sValue.charAt(nCount);
      nCount++;
    }
    i++;
  }

  objForm[strField].value = sCod;

  if (nTecla != 8) { // backspace
    if (sMask.charAt(i-1) == "9") { // apenas nmeros...
      return ((nTecla > 47) && (nTecla < 58)); } // nmeros de 0 a 9
    else { // qualquer caracter...
      return true;
    }
  }
  else {
    return true;
  }
}

function zero(tam, dec) {
  var x = 0;
  var retorno = '';
  for (x = tam; x < dec; x++) {
    retorno += '0';
  }
  return retorno;
}

function editDecMask(fld, milSep, decSep, mask, e) {
  var dec = 0;
  var mskLen = 0;
  var sep = 0;
  var key = '';
  var i = j = 0;
  var len = len2 = 0;
  var strCheck = '0123456789';
  var aux = aux2 = '';
  var whichCode = (window.Event) ? e.which : e.keyCode;
  var whichCodeDel = (window.Event) ? e.keyCode : e.keyCode;
  if (whichCode == 13) return true; // Enter
  if (whichCode == 8) return true; // BackSpace
  if (whichCodeDel == 46) return true; // Delete
  key = String.fromCharCode(whichCode); // Get key value from key code
  if (strCheck.indexOf(key) == -1) return false; // Not a valid key
  len = fld.value.length;
  for(i = 0; i < len; i++)
    if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
  aux = '';
  for(; i < len; i++)
    if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
  aux += key;
  len = aux.length;
  mskLen = mask.length;

  for (i = mskLen; i > 0; i--) {
    if (mask.charAt(i-1) == "." || mask.charAt(i-1) == ",") {break;}
    else {dec++;}
  }
    
  if (len == 0) fld.value = '';
  if (len < dec) fld.value = '0' + decSep + zero(len,dec) + aux;
  if (len == dec) fld.value = '0'+ decSep + aux;
  if (len > dec) {
    aux2 = '';
    for (j = 0, i = len - (dec + 1); i >= 0; i--) {
      if (j == 3) {
        aux2 += milSep;
        j = 0;
      }
      aux2 += aux.charAt(i);
      j++;
    }
    fld.value = '';
    len2 = aux2.length;
    for (i = len2 - 1; i >= 0; i--)
      fld.value += aux2.charAt(i);
    fld.value += decSep + aux.substr(len - dec, len);
  }
  return false;
}


function FormataCPF(Campo, teclapres){
	var tecla = teclapres.keyCode;
	
	var vr = new String(Campo.value);
	vr = vr.replace(".", "");
	vr = vr.replace(".", "");
	vr = vr.replace("-", "");

	tam = vr.length + 1;
	
	if (tecla != 9 && tecla != 8){
		if (tam > 3 && tam < 7)
			Campo.value = vr.substr(0, 3) + '.' + vr.substr(3, tam);
		if (tam >= 7 && tam <10)
			Campo.value = vr.substr(0,3) + '.' + vr.substr(3,3) + '.' + vr.substr(6,tam-6);
		if (tam >= 10 && tam < 12)
			Campo.value = vr.substr(0,3) + '.' + vr.substr(3,3) + '.' + vr.substr(6,3) + '-' + vr.substr(9,tam-9);
		}
}


//####################################################################//
// Funcoes abaixo sao usadas para controle de SELLOOKUPCOMBO/TEXTLOOKUP
//####################################################################//
var req = null;
var isIE;
var atualizado = true;
var lookupcomp, textcomp;
var XMLTEXTLOOKUP = "textlookup";
var XMLSELLOOKUPCOMBO = "sellookupcombo";

function RefreshLookup(link, idfield, typecomp) {
	var isTEXTLOOKUP = typecomp == XMLTEXTLOOKUP;
	var isSELLOOKUPCOMBO = typecomp == XMLSELLOOKUPCOMBO;
	if (isTEXTLOOKUP || !atualizado) {
		lookupcomp = document.getElementById(idfield);
		if (window.XMLHttpRequest) {
			req = new XMLHttpRequest();
			isIE = false;
			link += "&isIE=0";
		}
		else if (window.ActiveXObject) {
			req = new ActiveXObject("Microsoft.XMLHTTP");
			isIE = true;
			link += "&isIE=1";
		}
		if (isSELLOOKUPCOMBO || lookupcomp.value != "") {
			if (isTEXTLOOKUP)
				link += "&codtextlookup=" + lookupcomp.value;
//alert(link);				
			req.open("GET", link, true);
			if (isSELLOOKUPCOMBO)
				req.onreadystatechange = CallbackLookup;
			else {
				textcomp = document.getElementById("desc"+idfield);
				req.onreadystatechange = CallbackTextLookup;
			}
			req.send(null);
		}
		else if (isTEXTLOOKUP) {
			textcomp = document.getElementById("desc"+idfield);
			textcomp.innerHTML = "";
		}
	}
}   
function CallbackTextLookup() {
	if (req == null)
		return;
	if (req.readyState == 4) {
		if (req.status == 200) {
			textcomp.innerHTML = "&nbsp;" + req.responseXML.getElementsByTagName("desc")[0].childNodes[0].nodeValue + "&nbsp;";
			req = null;
		} 
		else {
			alert("Problema no retorno de dados XML do servidor: " + req.statusText);
			req = null;
		}
	}
}
function CallbackLookup() {
	if (req == null)
		return;
	if (req.readyState == 4) {
		if (req.status == 200) {
			ClearLookup();
			BuildLookup();
			req = null;
		} 
		else {
			alert("Problema no retorno de dados XML do servidor: " + req.statusText);
			req = null;
		}
	}
}
function ClearLookup() {
	while (lookupcomp.length > 0) {
		lookupcomp.remove(0);
	}
}
function BuildLookup() {
	var i = 0, j = 0, k;
	var s, cod, desc;
	var message = req.responseXML.getElementsByTagName("option")[0].childNodes[0].nodeValue;
        AppendLookup(lookupcomp, -1, document.createTextNode("-----"));
	while (message != "") {
		j = message.indexOf(";");
		s = message.substring(0,j);
		if (j == message.length)
			message = "";
		else
			message = message.substring(j+1);
		k = s.indexOf("-");
		desc = s.substring(0,k);
		cod = s.substring(k+1,s.length);
  	AppendLookup(lookupcomp, cod, document.createTextNode(desc));
	}
	atualizado = true;
}


function AppendLookup(select, value, content) {
    var opt;
    opt = document.createElement("option");
    opt.value = value;
    opt.appendChild(content);
    select.appendChild(opt);
}              



function RefreshLembrete(link, idfield) {   
    if (!atualizado) {        
        field = document.getElementById(idfield);        
        if (window.XMLHttpRequest) {            
            req = new XMLHttpRequest();            
            isIE = false;            
            link += "&isIE=0";            
        }
        
        else if (window.ActiveXObject) {            
            req = new ActiveXObject("Microsoft.XMLHTTP");            
            isIE = true;           
            link += "&isIE=1";            
        }       
        link += "&CPF=" + field.value;        
        req.open("GET", link, true);        
        textcomp = document.getElementById("pergunta");        
        req.onreadystatechange = CallbackLembrete;        
        atualizado = true;        
        req.send(null);       
    }   
}


function CallbackLembrete() {
    
    if (req == null)
        return;
    if (req.readyState == 4) {        
        if (req.status == 200) {            
            textcomp.innerHTML = "" + req.responseXML.getElementsByTagName("CPF")[0].childNodes[0].nodeValue + "&nbsp;";            
            req = null;            
        }        
        else {            
            alert("Problema no retorno de dados XML do servidor: " + req.statusText);            
            req = null;            
        }        
    }    
}



